package javase.ch03.homeWork.Test1;

/**
 * 银行账户类，支持存取款的线程安全操作
 */
public class Account {
    private Long id;
    private double balance;
    private String bankName;
    private static final double MAX_BALANCE = 10000.0; // 最大余额限制

    public Account(Long id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    public Account(String bankName, double balance) {
        this.bankName = bankName;
        this.balance = balance;
    }

    public synchronized void deposit(String person, double money) {
        // 如果余额已满，等待取款
        while (balance >= MAX_BALANCE) {
            System.out.println(person + "尝试存入" + money + "元，但余额已满(" + balance + "元)，等待取款...");
            try {
                wait(); // 释放锁并等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 执行存款
        balance += money;
        System.out.println(person + "存入" + money + "元，当前余额：" + balance + "元");

        // 如果余额达到10000元，唤醒等待取款的线程
        if (balance >= MAX_BALANCE) {
            notifyAll();
        }
    }

    public synchronized void withdraw(String person, double money) {
        // 如果余额不足，等待其他线程存款
        while (balance < money) {
            System.out.println(person + "尝试取款" + money + "元，余额不足(" + balance + "元)，等待存款...");
            try {
                wait(); // 释放锁并等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 余额充足时执行取款
        balance -= money;
        System.out.println(person + "取出" + money + "元，当前余额：" + balance + "元");

        // 如果余额为0，唤醒等待存款的线程
        if (balance == 0) {
            notifyAll();
        }
    }

    // getter和setter方法
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String getBankName() {
        return bankName;
    }

    public void setBankName(String bankName) {
        this.bankName = bankName;
    }
}
